package lab.cadl.lirui.markdown.core.utils

import lab.cadl.lirui.markdown.core.OutputFormat
import lab.cadl.lirui.markdown.core.exceptions.MarkdownException
import lab.cadl.lirui.markdown.core.parser.MarkdownParserFactory
import lab.cadl.lirui.markdown.core.renderers.HtmlRenderer
import lab.cadl.lirui.markdown.core.renderers.RenderOption
import lab.cadl.lirui.markdown.core.renderers.WordRenderer
import java.io.File

class DefaultRender {
    fun render(inputFile: File): File {
        return render(inputFile, "", OutputFormat.WORD)
    }

    fun render(inputFile: File, templateFile: String, format: OutputFormat): File {
        val baseDir = inputFile.parent ?: "./"
        val imageCache = ImageCacheImpl(baseDir)
        val document = MarkdownParserFactory(imageCache).create().parse(inputFile)
        println(document.debugDisplay())

        val renderer = when (format) {
            OutputFormat.WORD -> WordRenderer()
            OutputFormat.HTML -> HtmlRenderer()
            else -> throw MarkdownException("Unknown format: $format")
        }

        val outputDir = ""
        val originName = inputFile.nameWithoutExtension
        val destDir = if (outputDir.isBlank()) {
            baseDir
        } else {
            outputDir
        }

        return renderer.render(document, RenderOption(destDir, originName, templateFile, imageCache, renderer.defaultCustomOption()))
    }
}